/**
 * 
 */
package mblog.velocity.directive;

import java.io.IOException;

import javax.servlet.ServletRequest;

import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.tools.view.ViewToolContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.ServletRequestUtils;

import mblog.base.context.SpringContextHolder;
import mblog.base.lang.Consts;
import mblog.core.biz.PostBiz;
import mblog.velocity.BaseDirective;
import mblog.velocity.handler.RenderHandler;
import mtons.modules.pojos.Paging;

/**
 * 文章内容查询
 * 
 * 示例：
 * 	请求：http://mtons.com/index?ord=newest&pn=2
 *  使用：#contents(groupId, 'paging')
 *  解析： ord, pn 等参数从request中获取 , groupId 从标签中获取
 *  
 * @author langhsu
 *
 */
public class ContentsDirective extends BaseDirective {
	
	Logger logger  = LoggerFactory.getLogger(getClass());
	
	private PostBiz postPlanet;

	@Override
	public void initBean() {
		postPlanet = SpringContextHolder.getBean(PostBiz.class);
//		logger.debug("postPlanet/PostBiz class type is->" + postPlanet.getClass().getName()); 
	}

	@Override
	public String getName() {
		return "contents";
	}

	@Override
	public int getType() {
		return BLOCK;
	}
	
	//render：指令执行的入口
	//这里进行了一个参数的封装
	//render(InternalContextAdapter context, Writer writer, Node node)
	//RenderHandler 封装后的参数
	@Override
	public boolean render(RenderHandler handler) throws ResourceNotFoundException, ParseErrorException, MethodInvocationException, IOException {
		//(ViewToolContext)context.getInternalUserContext().getRequest()
		ServletRequest request = handler.getRequest();
		
		// request 获取参数
        String ord = ServletRequestUtils.getStringParameter(request, "ord", Consts.order.NEWEST);
        int pn = ServletRequestUtils.getIntParameter(request, "pn", 1);
        
        // 标签中获取参数
        //#contents(0, 'paging') (index.vm)
        //node.jjtGetChild(index)
        int groupId = handler.getIntParameter(0);
        String alias = handler.getStringParameter(1);
        
        //一个page对象，设置了请求页码
        Paging paging = wrapPaing(pn);
        
        //分页查询文章(关键在这里)
        //这里调用了PostBizImpl 里的paging方法，返回了查询文章结果
		Paging result = postPlanet.paging(paging, groupId, ord);
		
		logger.debug("ContentRender>>>ord : " + ord + " pn: " + pn + " groupId: " + groupId + " alias: " + alias); 
		
		handler.put(alias, result);
		//alias = $paging
//		#foreach($row in $paging.results)
//		#showBlog($row)
//		#end
		
		//渲染
		handler.doRender();
		//发布
		postRender(handler.getContext());
		return true;
	}

}
